﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;

namespace Sketch.Util
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args == null || args.Length == 0)
            {
                Console.WriteLine("Incorrect argument");                
                return;
            }

            if (args[0].Equals("-ClipAndResize", StringComparison.OrdinalIgnoreCase))
            {
                var mask = GetParameterValue(args, "Files");
                var targetDir = GetParameterValue(args, "TargetDir");
                var width = GetParameterValue(args, "Width");
                var height = GetParameterValue(args, "Height");                
                
                ClipAndResize(mask, new Size{Height = int.Parse(height), Width = int.Parse(width)}, targetDir);
            }

            Console.WriteLine("Done...");
            Console.ReadLine();
        }

        private static string GetParameterValue(IEnumerable<string> parameters, string parameterName)
        {
            var vlaue = parameters.Single(x => x.StartsWith(parameterName + "=", StringComparison.OrdinalIgnoreCase));
            vlaue = vlaue.Substring(vlaue.IndexOf("=") + 1);
            return vlaue;
        }

        public static void ClipAndResize(string filesMask, Size targetSize, string targetDir)
        {
            foreach (var file in Directory.GetFiles(Path.GetDirectoryName(filesMask), Path.GetFileName(filesMask)))
            {
                var image = Image.FromFile(file);
                image = ImageUtil.CropTransparentEdges(image);
                image = ImageUtil.Resize(image, targetSize);
                image = ImageUtil.PasteOnCavas(image, targetSize);

                image.Save(Path.Combine(targetDir, Path.GetFileName(file)), ImageFormat.Png);
                Console.WriteLine("Processed image {0}", Path.GetFileName(file));
            }
        }
    }
}
